#include "clientsocket.h"

ClientSocket::ClientSocket(QObject *parent)
    : QObject{parent}
{
    _socket = new QTcpSocket(this);
    m_recvBuffer.clear();
    connect(_socket, &QTcpSocket::connected, this, &ClientSocket::socketConnected);

    connect(_socket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::errorOccurred), this, &ClientSocket::socketError);

    connect(_socket, &QTcpSocket::readyRead, this, &ClientSocket::readData);

}

ClientSocket::~ClientSocket()
{
    if (_socket->isOpen()) {
        _socket->disconnectFromHost();
        _socket->waitForDisconnected();
    }
    delete _socket;
}

void ClientSocket::startConnection( QString serverAddress, quint16 serverPort)
{

    _socket->connectToHost(serverAddress, serverPort);
    //qDebug() << "startConnection"<<serverAddress<<serverPort<<_socket<<m_flag;
}

void ClientSocket::socketConnected()
{
    //qDebug() << "Connected to the server";
    // 发送请求数据给服务器
    bool ret;int len;
    //QString dnstr ="domain "+sendMsg;//netsol.com";
    if (_socket->state() == QTcpSocket::ConnectedState) {
        //len = socket->write(dnstr.toUtf8().data());
        len = _socket->write(m_sendMsg.toUtf8() + "\n");
        ret =_socket->flush();
        _socket->waitForBytesWritten();
        //qDebug() << "send data success."<<ret<<len<<_socket->socketDescriptor()<<m_sendMsg<<m_flag;
    } else {
        qDebug() << "send data fail."<<ret<<len<<m_sendMsg;
    }
}

void ClientSocket::socketError(QAbstractSocket::SocketError error)
{
    switch (error) {
    case QAbstractSocket::RemoteHostClosedError:
        //qDebug() << "Server has closed connection"<<_socket->socketDescriptor()<<m_flag<<m_recvBuffer.length();//<<m_recvBuffer;
        if(m_recvBuffer.length())//有数据才发送信息进行处理
        {
            emit dataReceived(m_recvBuffer,m_flag);
            //qDebug() <<"emit dataReceived "<<m_flag;
        }
        break;
    default:
        qWarning() << "An error occurred: " << _socket->errorString();

        break;
    }

}

void ClientSocket::readData()
{
    QByteArray data;
    while (_socket->bytesAvailable() > 0) {
        data = _socket->readAll();
        // 处理接收到的数据
        m_recvBuffer.append(data);
        //qDebug()<<"readData"<<_socket->socketDescriptor()<<m_flag<<data.length();
        //emit dataReceived(m_flag,data);
    }

}


